# -*- coding:utf-8 -*-

"""
商品标题黑名单DAO
"""

from sqlalchemy import select, update, delete
from sqlalchemy.ext.asyncio import AsyncSession

from module_admin.entity.do.title_blacklist_do import TitleBlacklist


class TitleBlacklistDao:
    """商品标题黑名单数据访问层"""
    
    @classmethod
    async def get_list(cls, db: AsyncSession, query_dict: dict = None, user_id: int = None):
        """
        获取标题黑名单列表（按用户隔离）
        
        Args:
            db: 数据库会话
            query_dict: 查询条件字典
            user_id: 用户ID，如果提供则只获取该用户的黑名单
        """
        query = select(TitleBlacklist).where(TitleBlacklist.del_flag == '0')
        
        # ✅ 用户隔离：只获取当前用户的黑名单
        if user_id is not None:
            query = query.where(TitleBlacklist.create_by == user_id)
        
        # 搜索条件
        if query_dict:
            if keyword := query_dict.get('keyword'):
                query = query.where(TitleBlacklist.keyword.like(f'%{keyword}%'))
            if match_type := query_dict.get('match_type'):
                query = query.where(TitleBlacklist.match_type == match_type)
        
        query = query.order_by(TitleBlacklist.create_time.desc())
        result = await db.execute(query)
        return result.scalars().all()
    
    @classmethod
    async def get_by_id(cls, db: AsyncSession, blacklist_id: int):
        """
        根据ID获取标题黑名单
        """
        query = select(TitleBlacklist).where(
            TitleBlacklist.id == blacklist_id,
            TitleBlacklist.del_flag == '0'
        )
        result = await db.execute(query)
        return result.scalar_one_or_none()
    
    @classmethod
    async def add(cls, db: AsyncSession, blacklist: TitleBlacklist):
        """
        新增标题黑名单
        """
        db.add(blacklist)
        await db.flush()
        return blacklist
    
    @classmethod
    async def update(cls, db: AsyncSession, blacklist_id: int, update_data: dict):
        """
        更新标题黑名单
        """
        query = update(TitleBlacklist).where(
            TitleBlacklist.id == blacklist_id,
            TitleBlacklist.del_flag == '0'
        ).values(**update_data)
        await db.execute(query)
    
    @classmethod
    async def delete(cls, db: AsyncSession, blacklist_id: int):
        """
        删除标题黑名单（软删除）
        """
        query = update(TitleBlacklist).where(
            TitleBlacklist.id == blacklist_id
        ).values(del_flag='2')
        await db.execute(query)
    
    @classmethod
    async def check_exists(cls, db: AsyncSession, keyword: str, user_id: int = None):
        """
        检查关键字是否已存在（按用户隔离）
        
        Args:
            db: 数据库会话
            keyword: 关键字
            user_id: 用户ID，如果提供则只检查该用户的黑名单
        """
        query = select(TitleBlacklist).where(
            TitleBlacklist.keyword == keyword,
            TitleBlacklist.del_flag == '0'
        )
        
        # ✅ 用户隔离：只检查当前用户的黑名单
        if user_id is not None:
            query = query.where(TitleBlacklist.create_by == user_id)
        
        result = await db.execute(query)
        return result.scalar_one_or_none() is not None

